package cn.jdy.framework.safe;

import java.nio.charset.Charset;

/**
 * 数据安全加密工具类 
 * 工具类具有的特点 
 *  1，对称加密 
 *  2，加密前后数据长度不变
 *  3，自定义密钥 
 *  4，支持中文
 * */
public class SecurityUtil {

    private static final String key0 = "FECOI()*&<MNCXZPKL";// 密钥
    private static final Charset charset = Charset.forName("GB18030");// 支持中文的编码设置
    private static byte[] keyBytes = key0.getBytes(charset);

    /**
     * 加密方法
     * */
    public static String encode(String enc) {
        byte[] b = enc.getBytes(charset);
        for (int i = 0, size = b.length; i < size; i++) {
            for (byte keyBytes0 : keyBytes) {
                b[i] = (byte) (b[i] ^ keyBytes0);
            }
        }
        return new String(b, charset);
    }

    /**
     * 解密方法
     * */
    public static String decode(String dec) {
        byte[] e = dec.getBytes(charset);
        byte[] dee = e;
        for (int i = 0, size = e.length; i < size; i++) {
            for (byte keyBytes0 : keyBytes) {
                e[i] = (byte) (dee[i] ^ keyBytes0);
            }
        }
        return new String(e, charset);
    }
    
    public static void main(String[] args) {
        String s = "you are right中文";
        String enc = encode(s);
        String dec = decode(enc);
        System.out.println("加密前 " + s);
        System.out.println("加密后 " + enc);
        System.out.println(enc.length());
        System.out.println("解密后 " + dec);
        System.out.println(dec.length());
    }
}
